<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="notes">
        <el-input
          v-model="queryParams.notes"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="处理回复" prop="reply">
        <el-input
          v-model="queryParams.reply"
          placeholder="请输入处理回复"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:feedback:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:feedback:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:feedback:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:feedback:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="feedbackList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="反馈ID" align="center" prop="id"/>
      <el-table-column label="用户名称" align="center" prop="userName"/>
      <el-table-column label="问题类型" align="center" prop="type">
        <template slot-scope="scope">
          {{ typeFormat(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="问题描述" align="center" prop="content"/>
      <el-table-column label="联系方式" align="center" prop="contact"/>
      <el-table-column label="邮箱" align="center" prop="email"/>
      <el-table-column label="备注" align="center" prop="notes"/>
      <el-table-column label="处理状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
            {{ scope.row.status === 0 ? '待处理' : '已处理' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="处理回复" align="center" prop="reply"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:feedback:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:feedback:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />

    <!-- 添加或修改问题反馈对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问题类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择问题类型" @change="handleTypeChange">
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" prop="userId">
          <el-select v-model="form.userName" placeholder="请选择用户" @change="handleUserChange">
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入问题描述"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入手机号码"/>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱地址"/>
        </el-form-item>
        <el-form-item label="提交时间" prop="createTime">
          <el-input v-model="form.createTime" :disabled="true"/>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">处理中</el-radio>
            <el-radio :label="1">已处理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" type="textarea" :rows="3" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="处理回复" prop="reply">
          <el-input v-model="form.reply" type="textarea" :rows="3" placeholder="请输入处理回复"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFeedback, getFeedback, delFeedback, addFeedback, updateFeedback, getUserList, getTypeList } from '@/api/system/feedback'

export default {
  name: 'Feedback',
  dicts: ['feedback_type'],  // 加载字典数据
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问题反馈表格数据
      feedbackList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        content: null,
        contact: null,
        email: null,
        notes: null,
        status: null,
        reply: null,
        userName: null
      },
      // 添加用户列表和类型列表
      userList: [],      // 用户列表
      typeList: [],      // 问题类型列表
      // 表单参数
      form: {
        id: null,
        typeId: null,        // 问题类型ID
        content: null,     // 问题描述
        contact: null,     // 手机号码
        email: null,       // 邮箱地址
        userId: null,      // 用户ID
        notes: null,       // 备注
        status: 0,         // 处理状态：0处理中，1已处理
        createTime: null,  // 提交时间
        updateTime: null,
        reply: null        // 处理回复
      },
      // 表单校验
      rules: {
        typeId: [
          { required: true, message: '请选择问题类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '问题描述不能为空', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '请选择用户', trigger: 'change' }
        ],
        userName: [
          { required: true, message: '请选择用户', trigger: 'change' }
        ]
      },
    }
  },
  created() {
    this.getList()
    this.getUsers()
    this.getTypes()
  },
  methods: {
    /** 查询问题反馈列表 */
    getList() {
      this.loading = true
      listFeedback(this.queryParams).then(response => {
        this.feedbackList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取用户列表 */
    getUsers() {
      getUserList().then(response => {
        this.userList = response.data || []
      })
    },
    /** 获取问题类型列表 */
    getTypes() {
      getTypeList().then(response => {
        console.log('问题类型列表响应:', response)
        if (response.code === 200) {
          this.typeList = response.data
        } else {
          this.$message.error(response.msg || '获取问题类型列表失败')
        }
      }).catch(error => {
        console.error('获取问题类型列表错误:', error)
        this.$message.error('获取问题类型列表失败')
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        typeId: null,
        content: null,
        contact: null,
        email: null,
        userId: null,
        userName: '',
        notes: null,
        status: 0,
        createTime: null,
        updateTime: null,
        reply: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加问题反馈'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      // 直接使用传入的行数据
      this.form = {
        ...row,
        id: row.id,
        typeId: row.typeId,
        content: row.content,
        contact: row.contact,
        email: row.email,
        userId: row.userId,
        userName: row.userName,
        notes: row.notes,
        status: row.status,
        reply: row.reply,
        createTime: row.createTime
      }
      
      // 获取类型列表和用户列表用于下拉选择
      Promise.all([getTypeList(), getUserList()]).then(([typeRes, userRes]) => {
        this.typeList = typeRes.data || []
        this.userList = userRes.data || []
        
        // 设置选中的类型和用户
        if (!this.form.typeId && this.form.typeId) {
          const selectedType = this.typeList.find(type => type.id === this.form.typeId)
          if (selectedType) {
            this.form.typeId = selectedType.id
          }
        }
        
        if (!this.form.userName && this.form.userId) {
          const selectedUser = this.userList.find(user => user.userId === this.form.userId)
          if (selectedUser) {
            this.form.userName = selectedUser.nickName
          }
        }
      })
      
      this.open = true
      this.title = '修改问题反馈'
    },
    /** 处理类型变化 */
    handleTypeChange(value) {
      const selectedType = this.typeList.find(type => type.id === value)
      if (selectedType) {
        this.form.typeName = selectedType.typeName
      }
    },
    /** 处理用户变化 */
    handleUserChange(value) {
      this.form.userName = value
      const selectedUser = this.userList.find(user => user.nickName === value)
      if (selectedUser) {
        this.form.userId = selectedUser.userId
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 构建提交数据，确保包含正确的ID和字段名
          const submitData = {
            ...this.form,
            typeId: this.typeList.find(t => t.typeName === this.form.typeName)?.id || this.form.typeId,
            userId: this.userList.find(u => u.nickName === this.form.userName)?.userId || this.form.userId,
            id: this.form.id,
            content: this.form.content,
            contact: this.form.contact,
            email: this.form.email,
            notes: this.form.notes,
            status: this.form.status,
            reply: this.form.reply
          }

          if (submitData.id != null) {
            updateFeedback(submitData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              } else {
                this.$modal.msgError(response.msg || '修改失败')
              }
            })
          } else {
            addFeedback(submitData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              } else {
                this.$modal.msgError(response.msg || '新增失败')
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除问题反馈编号为"' + ids + '"的数据项？').then(function() {
        return delFeedback(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/feedback/export', {
        ...this.queryParams
      }, `feedback_${new Date().getTime()}.xlsx`)
    },
    // 问题类型格式化
    typeFormat(row) {
      const type = this.typeList.find(item => item.id === row.typeId)
      return type ? type.typeName : ''
    },
    // 问题类型标签样式
    typeFilter(type) {
      return this.typeList.find(item => item.value === type)?.type || ''
    },
  }
}
</script>
